package Rangel.firebrigade.buildingdetector.targetselector.fullygreedy;

import Rangel.firebrigade.buildingdetector.FireBrigadeTarget;
import Rangel.firebrigade.buildingdetector.targetselector.DefaultFireBrigadeTargetSelector;
import Rangel.firebrigade.buildingdetector.targetselector.ZJUBaseBuildingCostComputer;
import Rangel.firebrigade.world.RangelFireBrigadeWorld;
import adf.agent.info.AgentInfo;
import Rangel.firebrigade.cluster.Cluster;
import Rangel.firebrigade.cluster.FireCluster;
import Rangel.common.world.sorter.ConstantComparators;
import Rangel.common.world.entity.RangelBuilding;
import rescuecore2.misc.Pair;
import rescuecore2.worldmodel.EntityID;

import java.util.*;

public class FullyGreedyTargetSelector extends DefaultFireBrigadeTargetSelector {
    public FullyGreedyTargetSelector(RangelFireBrigadeWorld world, AgentInfo agentInfo) {
        super(world,agentInfo);
        this.buildingCostComputer = new ZJUBaseBuildingCostComputer(world);
    }

    private ZJUBaseBuildingCostComputer buildingCostComputer;

    @Override
    public FireBrigadeTarget selectTarget(Cluster targetCluster) {

        FireBrigadeTarget fireBrigadeTarget = null;
        if (targetCluster != null) {
            target = calculateValueZJUBase((FireCluster) targetCluster);
            if (target != null) {
                lastTarget = target;
                fireBrigadeTarget = new FireBrigadeTarget(target, targetCluster);
            }
        }
        return fireBrigadeTarget;
    }

    private RangelBuilding calculateValueZJUBase(FireCluster fireCluster) {
        Set<RangelBuilding> buildings = fireCluster.getBuildings();
        RangelBuilding targetBuilding = null;
        SortedSet<Pair<EntityID, Double>> sortedBuildings = new TreeSet<>(ConstantComparators.DISTANCE_VALUE_COMPARATOR_DOUBLE);
        buildingCostComputer.updateFor(fireCluster, lastTarget);
        for (RangelBuilding building : buildings) {
            if (building.isBurning()) {
                building.BUILDING_VALUE = buildingCostComputer.getCost(building);
                sortedBuildings.add(new Pair<>(building.getID(), building.BUILDING_VALUE));
            }
        }
        if (!sortedBuildings.isEmpty()) {
            lastTarget = target;
            target = world.getRangelBuilding(sortedBuildings.first().first());
            targetBuilding = target;
        }
        return targetBuilding;
    }
}
